import { useEffect, useRef } from 'react';
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';
import './Map.css';

interface MapProps {
  mapRef: React.MutableRefObject<maplibregl.Map | null>;
  onMapLoad?: (map: maplibregl.Map) => void;
}

const Map = ({ mapRef, onMapLoad }: MapProps) => {
  const mapContainer = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!mapContainer.current) return;

    // 初始化地图
    mapRef.current = new maplibregl.Map({
      container: mapContainer.current,
      style: {
        version: 8,
        sources: {
          osm: {
            type: 'raster',
            tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
            tileSize: 256,
            attribution: '© OpenStreetMap Contributors'
          }
        },
        layers: [{
          id: 'osm',
          type: 'raster',
          source: 'osm',
          minzoom: 0,
          maxzoom: 19
        }]
      },
      center: [116.3972, 39.9075], // 北京市中心坐标
      zoom: 12,
      attributionControl: {
        compact: true
      }
    });

    // 地图加载完成后添加控件
    mapRef.current.on('load', () => {
      // 添加导航控件
      mapRef.current?.addControl(new maplibregl.NavigationControl(), 'top-right');
      
      // 尝试添加原生比例尺控件
      mapRef.current?.addControl(
        new maplibregl.ScaleControl({
          maxWidth: 150,
          unit: 'metric'
        }),
        'bottom-left'
      );
      
      // 调用外部回调
      onMapLoad?.(mapRef.current!);
      
      // 创建更好的自定义比例尺元素
      const mapContainer = document.getElementById('map');
      if (mapContainer && mapRef.current) {
        const existingScale = mapContainer.querySelector('.custom-scale');
        if (!existingScale) {
          // 创建比例尺容器
          const scaleContainer = document.createElement('div');
          scaleContainer.className = 'custom-scale';
          scaleContainer.style.position = 'absolute';
          scaleContainer.style.bottom = '10px';
          scaleContainer.style.left = '10px';
          scaleContainer.style.backgroundColor = 'rgba(255, 255, 255, 0.8)';
          scaleContainer.style.padding = '5px';
          scaleContainer.style.borderRadius = '3px';
          scaleContainer.style.fontSize = '10px';
          scaleContainer.style.color = '#333';
          scaleContainer.style.border = '1px solid #ccc';
          scaleContainer.style.zIndex = '1000';
          scaleContainer.style.display = 'flex';
          scaleContainer.style.flexDirection = 'column';
          scaleContainer.style.alignItems = 'center';
          
          // 创建比例尺线
          const scaleBar = document.createElement('div');
          scaleBar.style.height = '4px';
          scaleBar.style.backgroundColor = '#333';
          scaleBar.style.marginTop = '2px';
          scaleBar.style.position = 'relative';
          
          // 创建刻度线
          const leftTick = document.createElement('div');
          leftTick.style.position = 'absolute';
          leftTick.style.left = '0';
          leftTick.style.top = '0';
          leftTick.style.height = '8px';
          leftTick.style.width = '1px';
          leftTick.style.backgroundColor = '#333';
          leftTick.style.transform = 'translateY(-2px)';
          
          const rightTick = document.createElement('div');
          rightTick.style.position = 'absolute';
          rightTick.style.right = '0';
          rightTick.style.top = '0';
          rightTick.style.height = '8px';
          rightTick.style.width = '1px';
          rightTick.style.backgroundColor = '#333';
          rightTick.style.transform = 'translateY(-2px)';
          
          // 创建中间刻度线
          const middleTick = document.createElement('div');
          middleTick.style.position = 'absolute';
          middleTick.style.left = '50%';
          middleTick.style.top = '0';
          middleTick.style.height = '6px';
          middleTick.style.width = '1px';
          middleTick.style.backgroundColor = '#333';
          middleTick.style.transform = 'translateY(-2px) translateX(-50%)';
          
          // 添加刻度线到比例尺线
          scaleBar.appendChild(leftTick);
          scaleBar.appendChild(middleTick);
          scaleBar.appendChild(rightTick);
          
          // 创建文本标签
          const scaleText = document.createElement('div');
          scaleText.style.textAlign = 'center';
          scaleText.style.marginTop = '2px';
          
          // 添加元素到比例尺容器
          scaleContainer.appendChild(scaleText);
          scaleContainer.appendChild(scaleBar);
          
          // 更新比例尺
          const updateScale = () => {
            if (!mapRef.current) return;
            const zoom = mapRef.current.getZoom();
            // 根据缩放级别计算大致比例
            const metersPerPixel = 156543.03392 * Math.cos(mapRef.current.getCenter().lat * Math.PI / 180) / Math.pow(2, zoom);
            const width = 100; // 比例尺宽度（像素）
            const distance = Math.round(metersPerPixel * width);
            
            // 根据距离选择合适的单位
            let unit = 'm';
            let displayDistance = distance;
            if (distance >= 1000) {
              displayDistance = Math.round(distance / 100) / 10;
              unit = 'km';
            }
            
            // 调整宽度和文本
            scaleBar.style.width = `${width}px`;
            scaleText.textContent = `${displayDistance} ${unit}`;
          };
          
          // 初始更新和监听缩放事件
          updateScale();
          const map = mapRef.current;
          map.on('zoom', updateScale);
          map.on('move', updateScale);
          
          mapContainer.appendChild(scaleContainer);
        }
      }
    });

    // 清理函数
    return () => {
      mapRef.current?.remove();
    };
  }, []);

  return <div ref={mapContainer} id="map" />;
};

export default Map;